var Departamento = require('../classes/departamento');
var DepartamentoDAO = require('../DAO/departamento.dao');

function DepartamentoMapper() {
    var dao = new DepartamentoDAO();

    this.departamentoToModel = function(dep, callback) {
        var m = new dao.getModel();
        m.nome = dep.getNome();
        callback(m);
    }

    this.modelToDepartamento = function(m, callback) {
        if (m instanceof Array) {
            var out = [];
            m.forEach(function(i) {
                var dep = new Departamento();
                dep.setNome(i.nome);
                dep.setId(i._id);
                out.push(dep);
            });
            callback(out);
        }
        else {
            var dep = new Departamento();
            dep.setNome(m.nome);
            dep.setId(m._id);
            callback(dep);
        }
    }

    this.add = function(dep, callback) {
        var args = arguments;
        this.departamentoToModel(dep, function(m) {
            dao.add(m, callback);
        });
    }

    this.get = function(dep, callback) {
        var that = this;
        this.departamentoToModel(dep, function(m) {
            dao.get(m, function (err, data) {
                if(err) throw err;
                that.modelToDepartamento(data, function(d) {
                    callback(err, d);
                });
            });
        });
    }

    this.getById = function(id, callback) {
        var that = this;
        dao.getById(id, function(err, doc) {
            if(err) throw new Error('Not found!');
            that.modelToDepartamento(doc, function(dep) {
                callback(err, dep);
            });
        });
    }


    this.update = function(id, dep) {
        this.departamentoToModel(dep, function(m) {
            dao.update(id, m);
        });
    }

    this.remove = function(dep, callback) {
        this.departamentoToModel(dep, function(m) {
            dao.remove(m, callback);
        });
    }

    this.getAll = function(callback) {
        var that = this;
        dao.getAll(function(err, all) {
            that.modelToDepartamento(all, function(all) {
                callback(err, all);
            });
        });
    }
}

module.exports = DepartamentoMapper;
